package com.seehack.sample.springrest.httpclient.interceptor;

import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class ConnectionManagerStatusInterceptor implements HttpResponseInterceptor {

    private static final Logger log = LoggerFactory.getLogger(ConnectionManagerStatusInterceptor.class);

    private final PoolingHttpClientConnectionManager cm;

    public ConnectionManagerStatusInterceptor(PoolingHttpClientConnectionManager cm) {
        this.cm = cm;
    }

    public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
        Object httpRouteByContext = context.getAttribute(HttpClientContext.HTTP_ROUTE);
        if (httpRouteByContext instanceof HttpRoute) {
            // route status
            HttpRoute httpRoute = (HttpRoute) httpRouteByContext;
            log.info("route: {}, status: {}", httpRoute, cm.getStats(httpRoute));
        }
    }
}
